<template>
  <div class="main">
    <div class="main-title">添加入库信息</div>
    <div class="main-content">
      <el-row>
        <el-col :span="14">
          <el-form ref="inForm" label-width="120px" :model="inForm" :rules="inFormRules">
            <el-form-item label="入库类型" prop="instockType">
              <el-select placeholder="请选择入库类型" v-model="inForm.instockType">
                <el-option v-for="(item, index) in instockTypes.TypeArray" :key="index" :value="item.KeyId" :label="item.Value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="inForm.remark" type="textarea" :maxlength="1000" :autosize="{ minRows: 2, maxRows: 4}" style="width: 430px;"></el-input>
            </el-form-item>
            <el-form-item label="请选择商品">
              <el-select v-model="queryGood"
                filterable
                remote
                multiple
                :multiple-limit="1"
                placeholder="请输入商品名称|SPU"
                @focus="getGoodsList"
                :remote-method="remoteGoods"
                style="width: 430px; margin-right: 10px;">
                <el-option v-for="(item, index) in goodsList" :key="index" :label="item.commodityName" :value="item.commodityId"></el-option>
              </el-select><el-button type="primary" size="medium" @click="add">添加</el-button>
            </el-form-item>
            <el-form-item label="入库商品列表">
              <div class="instock-box">
                <div class="hd">
                  <div class="name">商品名称</div>
                  <div class="spu">SPU</div>
                  <div class="unit">规格</div>
                  <div class="sku">SKU</div>
                  <div class="stock">剩余库存</div>
                  <div class="num">入库数量</div>
                  <div class="operate">操作</div>
                </div>
                <div class="bd">
                  <!-- 商品 -->
                  <div class="item" v-for="(good, gi) in selectedGoodList" :key="gi">
                    <div class="name"><span class="center">{{good.commodityName}}</span></div>
                    <div class="spu"><span class="center">{{good.commodityNo}}</span></div>
                    <!-- 规格 -->
                    <div class="attr-box">
                      <div class="attr" v-for="(attr, ai) in good.attributes" :key="ai">
                        <div class="unit">{{attr.attributeName}}</div>
                        <div class="sku">{{attr.attributeSku}}</div>
                        <div class="stock">{{attr.stockNum}}</div>
                        <div class="num">
                          <el-input-number class="counter" v-model="attr.instockNum" :min="0" :precision="0" controls-position="right" size="mini"></el-input-number>
                        </div>
                      </div>
                    </div>
                    <div class="operate">
                      <span class="center"><el-button type="text" size="mini" @click="del(good.commodityId)">删除</el-button></span>
                    </div>
                  </div>
                  <div class="empty-box" v-if="!selectedGoodList.length">暂无商品</div>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div class="tools-wrapper" style="padding-left: 120px;">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="default" @click="cancel">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { instockTypes } from '@/data/enum'
export default {
  data () {
    return {
      instockTypes,
      inForm: {
        instockType: '',
        remark: '',
        indetails: []
      },
      inFormRules: {
        instockType: [
          {required: true, message: '请选择入库类型', trigger: 'change'}
        ]
      },
      queryGood: '', // 搜索商品（当前）
      goodsList: [], // 搜索商品列表
      selectedGoodList: [] // 选中的商品列表
    }
  },
  mounted () {
    this.selectedGoodList = JSON.parse(window.localStorage.getItem('selectedGoods')) || []
  },
  computed: {
    selGoodsNum () { // 是否输入了入库商品
      let count = 0
      this.selectedGoodList.forEach(good => {
        good.attributes.forEach(attr => {
          if (attr.instockNum) {
            count += attr.instockNum
          }
        })
      })
      return count
    }
  },
  methods: {
    // 获取商品列表
    getGoodsList () {
      return new Promise(resolve => {
        this.$http.post(this.$api + '/stock/getStockCommodityByKeyWord', {
          keyWord: ''
        }).then(res => {
          if (res.responseCode === '0000') {
            this.goodsList = res.data
          }
        })
        return resolve()
      })
    },
    // 远程搜索商品
    remoteGoods (str) {
      if (str !== '') {
        return new Promise(resolve => {
          this.$http.post(this.$api + '/stock/getStockCommodityByKeyWord', {
            keyWord: str
          }).then(res => {
            if (res.responseCode === '0000') {
              this.goodsList = res.data
            }
          })
          return resolve()
        })
      }
    },
    // 添加商品
    add () {
      let pId = this.queryGood[0]
      if (!pId) {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '请选择您要添加的商品！'
        })
        return false
      }
      if (!this.selectedGoodList.every(item => item.commodityId !== pId)) {
        this.$message.error({
          duration: this.$store.state.duration,
          message: '该商品已存在!',
          onClose: () => {
            this.queryGood = []
          }
        })
        return false
      }
      this.$http.post(this.$api + '/stock/getStockCommodityInfoByCommodityId', {
        commodityId: pId
      }).then(res => {
        if (res.responseCode === '0000') {
          res.data.attributes.forEach(attr => {
            this.$set(attr, 'instockNum', 0)
          })
          this.selectedGoodList.push(res.data)
          window.localStorage.setItem('selectedGoods', JSON.stringify(this.selectedGoodList))
          this.queryGood = []
        } else {
          this.$message.error({
            duration: this.$store.state.duration,
            message: res.responseMsg
          })
        }
      }).catch(err => {
        console.error(err)
      })
    },
    // 删除商品
    del (id) {
      let index = 0
      for (let i = 0; i < this.selectedGoodList.length; i++) {
        const item = this.selectedGoodList[i]
        if (item.commodityId === id) {
          index = i
        }
      }
      this.selectedGoodList.splice(index, 1)
      window.localStorage.setItem('selectedGoods', JSON.stringify(this.selectedGoodList))
    },
    // 保存入库单
    save () {
      this.$confirm('确定保存该入库单？').then(() => {
        this.$refs.inForm.validate(valid => {
          if (valid) { // 是否选择了入库类型
            if (this.selGoodsNum) { // 判断数量是否为0
              this.selectedGoodList.forEach(good => {
                good.attributes.forEach(attr => {
                  let obj = {
                    commodityId: good.commodityId,
                    attributeId: attr.attributeId,
                    stockNum: attr.stockNum,
                    instockNum: attr.instockNum
                  }
                  if (obj.instockNum) {
                    this.inForm.indetails.push(obj)
                  }
                })
              })
              let param = {
                instockType: this.inForm.instockType,
                remark: this.inForm.remark || '',
                indetails: JSON.stringify(this.inForm.indetails) || ''
              }
              this.$http.post(this.$api + '/stock/addCommodityInStock', param).then(res => {
                if (res.responseCode === '0000') {
                  this.$message.success({
                    duration: this.$store.state.duration,
                    message: '入库单保存成功！',
                    onClose: () => {
                      window.localStorage.removeItem('selectedGoods')
                      this.$router.push({
                        path: '/stock/importStock',
                        query: {
                          pg: this.$route.query.pg,
                          size: this.$route.query.size
                        }
                      })
                    }
                  })
                } else {
                  this.$message.error({
                    duration: this.$store.state.duration,
                    message: res.responseMsg
                  })
                }
              }).catch(err => {
                console.error(err)
              })
            } else {
              this.$message.error({
                duration: this.$store.state.duration,
                message: '入库商品数量不能为0！'
              })
            }
          } else {
            return false
          }
        })
      }).catch(_ => {})
    },
    // 取消
    cancel () {
      this.$confirm('确认取消保存该入库单？').then(() => {
        this.$message.info({
          duration: this.$store.state.duration,
          message: '操作成功！',
          onClose: () => {
            window.localStorage.removeItem('selectedGoods')
            this.$router.push({
              path: '/stock/importStock',
              query: {
                pg: this.$route.query.pg,
                size: this.$route.query.size
              }
            })
          }
        })
      }).catch(_ => {})
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
}
.instock-box {
  width: 961px;
  text-align: center;
  .name,
  .spu,
  .sku {
    width: 180px;
  }
  .num {
    width: 150px;
  }
  .unit,
  .stock,
  .operate {
    width: 90px;
  }
  .hd {
    height: 45px;
    line-height: 45px;
    background: #f8fcff;
    border-top: solid 1px #ebeef5;
    border-left: solid 1px #ebeef5;
    & > div {
      float: left;
      border-right: solid 1px #ebeef5;
    }
  }
  .bd {
    max-height: 400px;
    overflow: auto;
    background: #ffffff;
    border-top: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    .item {
      display: flex;
      justify-content: space-between;
      align-content: stretch;
      div {
        border-right: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
      }
      .operate {
        position: relative;
        width: 90px;
      }
      .name,
      .spu {
        position: relative;
        width: 180px;
      }
      .center {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        max-width: 160px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .attr-box {
        border: 0;
        .attr {
          display: flex;
          border: 0;
        }
        .counter {
          border: 0;
          width: 140px;
        }
      }
    }
  }
}
</style>
